/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package beans;

import entities.UserInfo;
import java.security.Principal;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;
import persistance.model.User;


/**
 *
 * @author Bobok
 */
public class LoginJSFBean {

    @EJB
    private UserDAOLocal userDAO;

    UserInfo userInfo = null;

    boolean loggedOff = false;

    /** Creates a new instance of LoginBean */
    public LoginJSFBean() {
    }

    public boolean isLogged() {
        if (loggedOff){
            userInfo = null;
            return false;
        }
        getUserInfo();
        return !(userInfo == null);
    }

    public boolean isAdmin() {
        return isLogged() && userInfo.isInRole("admin");
    }

    public boolean isModerator() {
        return isLogged() && userInfo.isInRole("moderator");
    }

    public boolean isEditor() {
        return isLogged() && userInfo.isInRole("editor");
    }

    public String getSignatureStyle(){
        if (!isLogged()){
            return "guestSignature";
        }
        if (userInfo.isInRole("admin")){
            return("adminSignature");
        }else if (userInfo.isInRole("moderator")){
            return("moderatorSignature");
        }else if (userInfo.isInRole("editor")){
            return("editorSignature");
        }
        return("guestSignature");
    }

    public UserInfo getUserInfo() {
        FacesContext ctx = FacesContext.getCurrentInstance();
        String remoteUser = ctx.getExternalContext().getRemoteUser();

        if (userInfo == null){            
            if (remoteUser != null){
                User user = userDAO.getUser(remoteUser);
                if (user != null){
                    userInfo = new UserInfo(user);
                }
            }
        }else{
            //this if for "na wszelki wypadek" ;)
            if (remoteUser == null){ //loged off!
                userInfo = null; //log off our data
            }
        }
        return userInfo;
    }

    public String logout(){
        FacesContext ctx = FacesContext.getCurrentInstance();
        HttpSession session = ((HttpSession)ctx.getExternalContext().getSession(false));
        if (session != null){
            session.invalidate();
            loggedOff = true;
            userInfo = null;
        }
        return "home";
    }

}
